/*
 登录
 * */
define(['../../common/service', '../../model/countryList',
    '../../model/timezoneList', 'sinput','drop', 'tip'], function( http, countryList,timezoneList) {
    var login = {
        init : function(){
            var _this = this;
            //配置I18N
            var sl = window.localStorage.getItem('language');
            if (sl && null != sl && 'null' != sl && 'undefined' != sl && undefined != sl){
                I18N.setLanguage(sl);
            } else {
                var _href = window.location.href;
                if (_href.indexOf("loginCn") > -1){
                    I18N.setLanguage('zh-cn');
                } else {
                    I18N.setLanguage('en-us');
                }
            }

            //根据分辨率加载不同的文字图片
            //if (screen.width <= 1400){
            //    var pI = $(".product-introduction").find("img");
            //    pI.attr("src",pI.attr("samll-src"));
            //} else {
            //    var pI = $(".product-introduction").find("img");
            //    pI.attr("src",pI.attr("big-src"));
            //}
            //
            //$(window).resize(function() {
            //    var width = $(this).width();
            //    console.log(width)
            //    if (width <= 1400){
            //        var pI = $(".product-introduction").find("img");
            //        pI.attr("src",pI.attr("samll-src"));
            //    } else {
            //        var pI = $(".product-introduction").find("img");
            //        pI.attr("src",pI.attr("big-src"));
            //    }
            //});


            $("div.ndp-sinput-wrapper[name=username]").sinput({
                xion:"<span><i class='font-icon font-icon-user'></i></span>",
                placeholder:I18N.getText("user", "unameOrEmail"),
                pos:"left",
                name: "username"
            });

            //记住我
            try{
                var rememberMeObj = window.localStorage.getItem('rememberMe');
                if(rememberMeObj && null != rememberMeObj && 'null' != rememberMeObj && 'undefined' != rememberMeObj && undefined != rememberMeObj){
                    rememberMeObj=JSON.parse(rememberMeObj);
                    if(rememberMeObj.rememberMe || rememberMeObj.rememberMe == 'true'){
                        $("#remember").prop("checked", rememberMeObj.rememberMe);
                        $("div.ndp-sinput-wrapper[name=username]").find("input").val(rememberMeObj.username);
                    }
                }
            }catch (e){
                console.error(e)
            }

            $("div.ndp-sinput-wrapper[name=password]").sinput({
                xion:"<span><i class='font-icon font-icon-lock'></i></span>",
                placeholder:I18N.getText("user", "password"),
                inputType:"password",
                pos:"left",
                name: "password"
            });

            //countryList.unshift({"val" : "-1", "text" : "国家"});
            var cL = countryList;
            $("div.ndp-drop-wrapper[name=country]").empty().drop({
                data:cL,
                caret:"glyphicon-menu-right",
                placeholder:I18N.getText("user", "country")
            }).on("ITEM_CLICK", function(e){
                var _e = $("div.ndp-drop-wrapper[name=country]");
                _e.removeClass("form-input-warning");
                _e.parents(".s-item").find(".warning-r").addClass("hide");
            });

            //timezoneList.unshift({"val" : "-1", "text" : "时区"});
            var tL = timezoneList;
            $("div.ndp-drop-wrapper[name=timezone]").empty().drop({
                data:tL,
                caret:"glyphicon-menu-right",
                placeholder:I18N.getText("user", "timezone")
            }).on("ITEM_CLICK", function(e){
                var _e = $("div.ndp-drop-wrapper[name=timezone]");
                _e.removeClass("form-input-warning");
                _e.parents(".s-item").find(".warning-r").addClass("hide");
            });

            //语言
            var locales = [{"val" : "zh-cn", "text" : "汉语(简)"}, {"val" : "en-us", "text" : "English(us)"}];
            $("div.ndp-drop-wrapper[name=locale]").empty().drop({
                data:locales,
                caret:"glyphicon-menu-right",
                placeholder:I18N.getText("user", "locale")
            }).on("ITEM_CLICK", function(e){
                var _e = $("div.ndp-drop-wrapper[name=locale]");
                _e.removeClass("form-input-warning");
                _e.parents(".s-item").find(".warning-r").addClass("hide");
            });

            $(".forget-area").find("div.ndp-sinput-wrapper[name=email]").empty().sinput({
                xion:"<span><i class='font-icon font-icon-mail'></i></span>",
                placeholder:I18N.getText("user", "email"),
                pos:"left"
            });

            _this.event();

        },
        event : function(){
            var _this = this;
            //注册
            $(".sign-link").off("click").on("click", function(e){
                $(".p-container").removeAttr("class").addClass("p-container").addClass("sign-area-c");
                $(".login-area").addClass("hide");
                $(".forget-area").addClass("hide");
                //清空数据
                _this.cleearData();
                $(".sign-area").removeClass("hide");
            });

            //返回登录
            $(".r-login").off("click").on("click", function(e){
                $(".p-container").removeAttr("class").addClass("p-container").addClass("login-area-c");
                $(".login-area").removeClass("hide");
                $(".forget-area").addClass("hide");
                //清空数据
                _this.cleearData();
                $(".sign-area").addClass("hide");
            })

            //忘记密码
            $(".forget-link").off("click").on("click", function(e){
                $(".p-container").removeAttr("class").addClass("p-container").addClass("forget-area-c");
                $(".login-area").addClass("hide");
                $(".sign-area").addClass("hide");
                //清空数据
                _this.cleearData();
                $(".forget-area").removeClass("hide");
                $(".forget-area").find("div.ndp-sinput-wrapper[name=email]").empty().sinput({
                    xion:"<span><i class='font-icon font-icon-mail'></i></span>",
                    placeholder:I18N.getText("user", "email"),
                    pos:"left"
                });
            });

            //想起密码
            $(".r-password").off("click").on("click", function(e){
                $(".forget-area").addClass("hide");
                $(".sign-area").addClass("hide");
                $(".login-area").removeClass("hide");
                //清空数据
                _this.cleearData();

            });

            //输入框输入事件
            $(".p-container").off("input", "input").on("input","input",function(e){
                $(this).removeClass("form-input-warning");
                $(this).parents(".form-input-warning").removeClass("form-input-warning");
                $(this).parents(".s-item").find(".warning-r").addClass("hide");
            })
            //注册相关事件
            _this.signEvents();
            //注册事件
            _this.signEvent();
            _this.loginEvens();
            //登录事件
            _this.loginEvent();
            //找回密码事件
            _this.findEvent();
        },
        loginEvens : function(){
            var _loginArea = $(".login-area");
            var _usernameE = _loginArea.find("div.ndp-sinput-wrapper[name=username]").find("input");
            var _passwordE = _loginArea.find("div.ndp-sinput-wrapper[name=password]").find("input");

            //登录用户名输入enter，光标自动移到登录密码
            _usernameE.unbind('keydown');
            _usernameE.keydown(function(e){
                if(e.keyCode == 13){
                    e.preventDefault();
                    if($.trim($(this).val()) != '')
                        _passwordE.focus();
                }
            });
            //登录密码输入enter，自动触发登录
            _passwordE.unbind('keydown');
            _passwordE.keydown(function(e){
                if(e.keyCode == 13)
                    _loginArea.find(".login").trigger('click');
            });
        },
        signEvents : function(){
            var _this = this;
            var _signArea = $(".sign-area");
            //用户名
            var _usernameE = _signArea.find('input[name="username-s"]');
            //邮箱
            var _emailE = _signArea.find('input[name="email-s"]');
            //邀请码
            var _invitationCodeE = _signArea.find('input[name="invitationCode"]');

            // 绑定用户名称失去焦点时的校验事件
            _usernameE.off("blur").bind("blur", function () {
                var _unv = _usernameE.val().trim();
                if ('' == _unv){
                    return false;
                }
                var param = {
                    username: _unv
                };
                http.work('/login/find',param,'POST').then(function(res){
                    if(res.flag == 'success'){
                        _this.showInputError(_usernameE, I18N.getText('user','usernamehas'), true, true);
                        _this.isUserNameValid = false;
                    }else{
                        _this.isUserNameValid = true;
                    }
                });
            });

           // 绑定邮箱失去焦点时的校验事件
            _emailE.off("blur").bind("blur", function () {
                var _emailv = _emailE.val().trim();
                if ('' == _emailv){
                    return false;
                }
                var param = {
                    email:_emailv
                };
                http.work('/login/find',param,'POST').then(function(res){
                    if(res.flag == 'success'){
                        _this.showInputError(_emailE, I18N.getText('user','emailhas'), true, true);
                        _this.isEmailValid = false;
                    }else{
                        _this.isEmailValid = true;
                    }
                });
            });

            // 绑定邀请码失去焦点时的校验事件
            _invitationCodeE.off("blur").bind("blur", function () {
                var _invitationCodev = _invitationCodeE.val().trim()
                if ('' == _invitationCodev){
                    return false;
                }

                var param = {
                    invitationCode: _invitationCodeE.val().trim()
                };
                http.work('/login/validateInvitationCode',param,'POST').then(function(res){
                    if(res.flag == 'fail'){
                        _this.showInputError(_invitationCodeE, I18N.getText('user','invitationCodeTtl'), true, true);
                        _this.isInvitationCodeValid = false;
                    }else{
                        _this.isInvitationCodeValid = true;
                    }
                });
            });

            //注册区域 密码input获取焦点 改type为password
            var  _password = _signArea.find('input[name="password-s"]');
            var  _confirmPassword = _signArea.find('input[name="confirmPassword"]');
            _confirmPassword.off("focus").on("focus", function(){
                _confirmPassword.attr("type", "password");
            })
            _password.off("focus").on("focus", function(){
                _password.attr("type", "password");
            })

        },
        findEvent : function(){
            var _this = this;
            $(".find").off("click").on("click", function(e){
                $(".error-s").addClass("hide");
                var _fArea = $(".forget-area");
                var _emailE = _fArea.find("div.ndp-sinput-wrapper[name=email]");
                var _email = $.trim(_emailE.find("input").val());

                if (_email == ''){
                    _this.showInputError(_emailE, I18N.getText('user','enteremail'));
                    return false;
                }

                var strRegex = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
                var reg = new RegExp(strRegex);
                if (!reg.test(_email)) {
                    _this.showInputError(_emailE, I18N.getText('user','emailTypeError'));
                    return false;
                }

                var param = {
                    email: _email
                };
                var loadingArea = $('.content-block');
                Kit.loading.show(loadingArea);
                http.work('/login/doforget',param,'POST').then(function(res){
                    if(res.flag == 'success'){
                        window.location.href = "login.html";
                    }else{
                        _this.showDangerTip($(".error-s"), "danger", res.msg || I18N.getText('user','forgetpwdFail'))
                    }
                }).done(function(){
                    Kit.loading.hide(loadingArea);
                });
            });
        },
        loginEvent : function(){
            var _this = this;
            $(".login").off("click").on("click", function(e){
                $(".error-s").addClass("hide")
                var _loginArea = $(".login-area");
                var _usernameE = _loginArea.find("div.ndp-sinput-wrapper[name=username]");
                var _username = $.trim(_usernameE.find("input").val());
                var _passwordE = _loginArea.find("div.ndp-sinput-wrapper[name=password]");
                var _password = $.trim(_passwordE.find("input").val());

                if(_username == ''){
                    _this.showInputError(_usernameE, I18N.getText('user','enterUnameOrEmail'));
                    return false;
                }

                if(_password == ''){
                    _this.showInputError(_passwordE, I18N.getText('user','enterPassword'));
                    return false;
                }

                var param = {
                    "username": _username,
                    "password": _password
                };
                var loadingArea = $('.content-block');
                Kit.loading.show(loadingArea);
                http.work('/logusers/login',param,'POST').then(function(res){
                    if(res.flag == 'success'){
                        window.sessionStorage.clear();
                        //window.localStorage.clear();
                        var data = res.data;
                        var userInfo = data.userInfo;
                        localStorage.setItem('uName',userInfo.username);
                        localStorage.setItem('language',userInfo.language);
                        if($('#remember').is(':checked')){//记住我
                            var rememberMeObj = {
                                rememberMe:true,
                                username:userInfo.username
                            }
                            localStorage.setItem('rememberMe',JSON.stringify(rememberMeObj));
                        }else{
                            localStorage.removeItem('rememberMe');
                        }
                        window.sessionStorage.setItem('timezone',userInfo.timezoneId);
                        window.sessionStorage.setItem('roleIds',userInfo.roleId);
                        var _href = window.location.href;
                        var _url = _href.split('gotoUrl=')[1];
                        window.location.href = _url ? _url : "index.html";
                    }
                    else{
                        _this.showDangerTip($(".error-s"),"danger", res.msg);
                    }
                }).done(function(){
                    Kit.loading.hide(loadingArea);
                })
            })
        },
        cleearData : function(){
            $(".p-container").find(".error-s").addClass("hide");
            $(".p-container").find(".form-input-warning").removeClass("form-input-warning").removeClass("can-clear");
            $(".p-container").find(".warning-r").addClass("hide");
            $(".p-container").find("input").val("");
            //$("div.ndp-sinput-wrapper[name=username]").find("input").empty();
            //$("div.ndp-sinput-wrapper[name=password]").find("input").empty();
            $("div.ndp-sinput-wrapper[name=username]").empty().sinput({
                xion:"<span><i class='font-icon font-icon-user'></i></span>",
                placeholder:I18N.getText("user", "unameOrEmail"),
                pos:"left",
                name: "g",
                autocomplete:"off"
            });

            $("div.ndp-sinput-wrapper[name=password]").empty().sinput({
                xion:"<span><i class='font-icon font-icon-lock'></i></span>",
                placeholder:I18N.getText("user", "password"),
                inputType:"password",
                pos:"left",
                name: "g",
                autocomplete:"off"
            });

            $.each($(".p-container").find("div.ndp-drop-wrapper"), function(i, _e){
                $(_e).drop("val", "");
            });
        },
        showDangerTip : function(_bE, _type, _content){
            _bE.removeClass("hide");
            _bE.find(".msg").html(_content);
        },
        signEvent : function(){
            var _this = this;
            $(".sign").off("click").on("click", function(e){
                $(".error-s").addClass("hide")
                //先将所有提示清空
                $.each($(".p-container").find(".can-clear"), function(i, _e){
                    $(_e).removeClass("form-input-warning").removeClass("can-clear");
                    $(_e).parents(".s-item").find(".warning-r").addClass("hide");
                })

                var _signArea = $(".sign-area");
                //用户名
                var _usernameE = _signArea.find('input[name="username-s"]');
                var _username = _usernameE.val();
                //邮箱
                var _emailE = _signArea.find('input[name="email-s"]');
                var _email = _emailE.val();
                //密码
                var _passwordE = _signArea.find('input[name="password-s"]');
                var _password = _passwordE.val();
                //确认密码
                var _confirmPasswordE = _signArea.find('input[name="confirmPassword"]');
                var _confirmPassword = _confirmPasswordE.val();
                //昵称
                var _nicknameE = _signArea.find('input[name="nickname"]');
                var _nickname = _nicknameE.val();
                //邀请码
                var _invitationCodeE = _signArea.find('input[name="invitationCode"]');
                var _invitationCode = _invitationCodeE.val();
                //国家
                var _countryE = _signArea.find('div[name="country"]');
                var _country = _countryE.drop("data");
                //timezone
                var _timezoneE = _signArea.find('div[name="timezone"]')
                var _timezone = _timezoneE.drop("data");
                //locale
                var _localeE = _signArea.find('div[name="locale"]');
                var _locale = _localeE.drop("data");
                //校验用户名
                if (_username == ''){
                    _this.showInputError(_usernameE, I18N.getText('user','enterName'));
                    return false;
                }

                if (!/^[a-zA-Z0-9_]{3,16}$/.test(_username)) {
                    _this.showInputError(_usernameE, I18N.getText('user','usernameError'));
                    return false;
                }

                if (!_this.isUserNameValid){
                    _this.showInputError(_usernameE, I18N.getText('user','usernamehas') ,true ,true);
                    return false;
                }

                //邮箱
                if (_email == ''){
                    _this.showInputError(_emailE, I18N.getText('user','enteremail'));
                    return false;
                }
                var strRegex = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
                var reg = new RegExp(strRegex);
                if (!reg.test(_email)) {
                    _this.showInputError(_emailE, I18N.getText('user','emailTypeError'));
                    return false;
                }

                if (!_this.isEmailValid){
                    _this.showInputError(_emailE, I18N.getText('user','emailhas') ,true ,true);
                    return false;
                }

                //密码
                if ('' == _password) {
                    _this.showInputError(_passwordE, I18N.getText('user','enterPassword'));
                    return false;
                }
                if (_password.length < 6) {
                    _this.showInputError(_passwordE, I18N.getText('user','passwordmin'));
                    return false;
                }

                //确认密码
                if ('' == _confirmPassword) {
                    _this.showInputError(_confirmPasswordE, I18N.getText('user','enterPasswordAgain'));
                    return false;
                }
                if (_confirmPassword.length < 6) {
                    _this.showInputError(_confirmPasswordE, I18N.getText('user','passwordmin'));
                    return false;
                }

                if (_password != _confirmPassword) {
                    _this.showInputError(_confirmPasswordE, I18N.getText('user','enterPasswordDiff'));
                    return false;
                }

                if ('' == _nickname) {
                    _this.showInputError(_nicknameE, I18N.getText('user','enternickname'));
                    return false;
                }

                if ('' == _invitationCode){
                    _this.showInputError(_invitationCodeE, I18N.getText('user','enterinvitationCode'));
                    return false;
                }else{
                    if (!_this.isInvitationCodeValid) {
                        _this.showInputError(_invitationCodeE, I18N.getText('user','invitationCodeTtl') ,true ,true);
                        return false;
                    }
                }

                if ('' == _country.val) {
                    _this.showInputError(_countryE, I18N.getText('user','selectCountry'));
                    return false;
                }

                if ('' == _timezone.val) {
                    _this.showInputError(_timezoneE, I18N.getText('user','selectTimezone'));
                    return false;
                }

                if ('' == _locale.val) {
                    _this.showInputError(_localeE, I18N.getText('user','selectLocale'));
                    return false;
                }

                var param = {
                    username: _username,
                    email: _email,
                    password: _password,
                    nickname: _nickname,
                    invitationCode:_invitationCode,
                    country: _country.val,
                    timezoneId: _timezone.val,
                    timezoneName: _timezone.txt,
                    language:_locale.val
                };

                var loadingArea = $('.content-block');
                Kit.loading.show(loadingArea);
                http.work('/login/register',param,'POST').then(function(res){
                    if(res.flag == 'success'){
                        window.location.href = "login.html";
                    }else{
                        _this.showDangerTip($(".error-s"), "danger", res.msg || I18N.getText('user','registerFail'));
                    }

                }).done(function(){
                    Kit.loading.hide(loadingArea);
                });
            })
        },
        showInputError : function(_e, _msg, _isNotFocus, _isNotClear){
            console.log(_msg)
            $(_e).addClass("form-input-warning");
            if (!_isNotClear){
                $(_e).addClass("can-clear");
            }
            if (!_isNotFocus){
                $(_e).focus();
                $(_e).find("input").focus();
            }
            $(_e).parents(".s-item").find(".warning-r").html(_msg).removeClass("hide")
        }
    }
    login.init();
})
